package com.wn.icloud.controller;

import com.wn.icloud.common.context.BaseContextHandler;
import com.wn.icloud.domain.BaseEntityDomain;
import com.wn.icloud.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;

public class BaseController<Entity extends BaseEntityDomain, ID extends Serializable, Service extends BaseService<Entity, ID>> {

    @Autowired
    public Service service;

    @Autowired
    protected HttpServletRequest request;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public Entity add(@RequestBody Entity entity) {
        service.save(entity);

        return entity;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Optional<Entity> get(@PathVariable ID id) {
        return service.findById(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public Entity update(@RequestBody Entity entity) {
        service.save(entity);
        return entity;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void remove(@PathVariable ID id) {
        service.deleteById(id);
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public List<Entity> all() {
        return service.findAll();
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Page<Entity> list(Pageable pageable) {
        //查询列表数据
        return service.findAll(pageable);
    }

    public String getCurrentUserName() {
        return BaseContextHandler.getUsername();
    }


}